package me.spring.cloud.components.starter.cat.dynamic;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import me.spring.cloud.common.components.monitor.constant.Constant;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author: luffy
 * @create: 2018-09-12 18:06
 **/
@Slf4j
public class DynamicCatMonitorConfiguration implements ApplicationContextAware {

  private ApplicationContext applicationContext;

  @ApolloConfigChangeListener(interestedKeyPrefixes = Constant.cat_monitor_level_prefix)
  private void onChange(ConfigChangeEvent changeEvent) {
    refreshProperties(changeEvent.changedKeys());
  }

  private void refreshProperties(Set<String> changedKeys) {
    this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}
